package com.flexrrb.managers
{
	import com.flexrrb.core.RRBTooltipConfigItem;
	
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.core.IUIComponent;
	import mx.core.UIComponent;
	import mx.managers.ISystemManager;
	
	public class RRBTooltipManager
	{
		private static var _instance:RRBTooltipManager;
		private var _objects:Dictionary;
		
		public function RRBTooltipManager(se:SingletonEnforcer)
		{
			_objects = new Dictionary(true);	
		}
		
		public static function getInstance():RRBTooltipManager
		{
			if(!_instance)
			{
				_instance = new RRBTooltipManager(new SingletonEnforcer());
			}
			
			return _instance;
		}
		
		public function set targets(value:ArrayCollection):void
		{
			for each(var item:RRBTooltipConfigItem in value)
			{
				addTarget(item);
			}
		}
		
		public function addTarget(value:RRBTooltipConfigItem):void
		{
			if(value && value.target.toolTip)
			{
				_objects[value.target] = value;
				initializeItem(value);
			}
		}
		
		public function removeTarget(target:UIComponent, restore:Boolean=true):void
		{
			var configItem:RRBTooltipConfigItem = getConfigItem(target);
			if(configItem)
			{
				if(restore)
					configItem.target.toolTip = configItem.tooltip.text;
					
				_objects[target] = null;
				delete _objects[target];
			}
		}
		
		private function getConfigItem(target:Object):RRBTooltipConfigItem
		{
			return _objects[target] as RRBTooltipConfigItem;
		}
		
		private function initializeItem(item:RRBTooltipConfigItem):void
		{
			item.target.addEventListener(MouseEvent.ROLL_OVER, onMouseOver, false, 0, true);
			item.target.addEventListener(MouseEvent.ROLL_OUT, onMouseOut, false, 0, true);
		}
		
		private function onMouseOver(event:MouseEvent):void
		{
			var configItem:RRBTooltipConfigItem = getConfigItem(event.currentTarget);
			if(configItem)
			{
				
				var sm:ISystemManager = getSystemManager(configItem.target as DisplayObject);
				sm.topLevelSystemManager.addChildToSandboxRoot("toolTipChildren", configItem.tooltip as DisplayObject);
       			
				configItem.tooltip.setupPosition();
			}
		}
		
		public function getSystemManager(target:DisplayObject):ISystemManager
	     {
	        return target is IUIComponent ?
	               IUIComponent(target).systemManager :
	               null;
	     }
		
		private function onMouseOut(event:MouseEvent):void
		{
			var configItem:RRBTooltipConfigItem = _objects[event.currentTarget] as RRBTooltipConfigItem;
			if(configItem)
			{
				var sm:ISystemManager = getSystemManager(configItem.tooltip as DisplayObject);
				sm.topLevelSystemManager.removeChildFromSandboxRoot("toolTipChildren", configItem.tooltip as DisplayObject);
   			}
		}
	}
}

class SingletonEnforcer{}